package com.jasiri.project.lib.dev.data

import android.Manifest
import android.content.Context
import android.content.pm.ApplicationInfo
import android.content.pm.PackageManager
import android.os.Build
import com.google.gson.Gson
import com.jasiri.project.lib.dev.util.formatZipString

/**
 * AppList
 */
class JasiriSysDataT6(val context: Context) {

    fun getSubmitDataT6(): String? {
        return try {
            val array = arrayOf(
                Manifest.permission.INTERNET,
                Manifest.permission.ACCESS_NETWORK_STATE
            )

            val flags = PackageManager.GET_ACTIVITIES or PackageManager.GET_META_DATA
            val packages = context.packageManager.getPackagesHoldingPermissions(array, flags)

            val dataList = mutableListOf<HashMap<String, Any>>()
            for (item in packages) {
                val obj = item.applicationInfo

                obj?.let {

                    // 过滤掉系统应用
                    val cSY = (obj.flags and ApplicationInfo.FLAG_SYSTEM != 0)
                    if (!cSY) {
                        val appName = obj.loadLabel(context.packageManager).toString()
                        val appVersionCode = if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
                            item.versionCode.toString()
                        } else {
                            item.longVersionCode.toString()
                        }

                        val jsonObject = HashMap<String, Any>().apply {
                            put("appType", 0)
                            put("appName", appName)
                            put("appVersionCode", appVersionCode)
                            put("dataPath", obj.dataDir ?: "")
                            put("sourcePath", obj.sourceDir ?: "")
                            put("appPackageName", item.packageName ?: "")
                            put("appVersionName", item.versionName ?: "")
                            put("installTime", item.firstInstallTime.toString())
                            put("lastTime", item.lastUpdateTime.toString())
                            put("flags", obj.flags.toString())
                        }
                        dataList.add(jsonObject)
                    }
                }
            }

            Gson().toJson(dataList).trim().formatZipString()

        } catch (e: Exception) {
            null
        }
    }
}